package com.peanut.search.service;

import java.util.List;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.peanut.common.utils.MapperUtil;
import com.peanut.search.mapper.CarMapper;
import com.peanut.common.pojo.Car;

@Service
public class CreateIndexService {
	@Autowired
	private CarMapper carMapper;
	@Autowired
	private TransportClient client;
	
	public void createIndex() throws Exception {
		/*读取源数据 select * from t_product limit 0,100
		 *List<Product>
		 *整理成document 通过调用transportclient写入到索引中
		 *创建索引,for循环list挨个写入 product-->json
		 */
		List<Car> pList = carMapper.queryCars(0,100);
		//创建索引 peanut
		client.admin().indices().prepareCreate("peanut").get();
		//for循环添加document
		for (Car car: pList) {
			//先把car序列化成json
			String json = MapperUtil.MP.writeValueAsString(car);
			IndexRequestBuilder request = 
			client.prepareIndex("peanut", "car", car.getCarId());
			//添加request参数 json
			request.setSource(json).get();
		
		}
	}
	
	
	
	
}
